package com.wjf.accesscontrol.ui.main

import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.wjf.accesscontrol.net.api.ApiHelper
import com.wjf.accesscontrol.net.api.RetrofitBuilder
import com.wjf.accesscontrol.net.utils.Resource
import com.wjf.accesscontrol.util.Constant
import com.wjf.accesscontrol.util.TimeUtils
import org.json.JSONArray
import org.json.JSONObject

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2024/2/1 14:28
 *
 */

class MainViewModel: ViewModel() {

    fun stationDetail() = liveData {
        emit(Resource.loading(data = null))
        try {
            Constant.serviceId = "station"
            Constant.serviceMethod = "stationDetail"

            emit(Resource.success(baseBean = ApiHelper.stationDetail(Constant.baseUrl, Constant.machineId)))
        } catch (exception: Exception) {
            emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
        }
    }

    fun upload(idNum: String, name: String, sex: String, accessType: Int) = liveData {
        emit(Resource.loading(data = null))
        try {
            Constant.serviceId = "hikAccessLog"
            Constant.serviceMethod = "upload"

            val jsonObject = JSONObject()
            try {
                jsonObject.put("type",0)
                jsonObject.put("source", Constant.region)
                jsonObject.put("isThirdParty",false)
                val jsonArray = JSONArray()
                val jsonInfo = JSONObject()
                //需要每次都不一样
                jsonInfo.put("upId",System.currentTimeMillis())
                jsonInfo.put("certificateNo",idNum)
                jsonInfo.put("upStationId", Constant.stationId)
                jsonInfo.put("accessType",accessType)
                jsonInfo.put("userName",name)
                jsonInfo.put("sex",sex)
                jsonInfo.put("createTime", TimeUtils.instance.getTime(pattern = "yyyy-MM-dd HH:mm:ss"))
                jsonInfo.put("province", Constant.province)
                jsonInfo.put("city", Constant.city)
                jsonInfo.put("region", Constant.region)
                jsonArray.put(jsonInfo)
                jsonObject.put("hikAccessLogDTOS",jsonArray)

            } catch (e: Exception) {
            }

            emit(
                Resource.success(baseBean = ApiHelper.upload(
                    Constant.uploadUrl,
                    RetrofitBuilder.getRequestBody(jsonObject.toString())
                )))
        } catch (exception: Exception) {
            emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
        }
    }

}